import { useEffect, useState } from 'react'
import { Result } from 'ahooks/lib/useRequest/src/types'
import { Button, Card, Col, Form, Row } from 'antd'

import { TAddressListRes } from '@oBiz/hooks/SWRApi/useAddressList'
import { useBoundStore } from '../../store'
import { getBatchActionConfig } from './config'
import { IBatchAction, TFormItem, TOperationType } from './interface'
import styles from './styles.module.less'

export const BatchAction = ({
  operationType,
  addressList,
}: {
  operationType: TOperationType
  addressList: Result<TAddressListRes, []>
}) => {
  const form = Form.useFormInstance()
  const eventList = useBoundStore(state => state.eventList)
  const [schemaConfig, setSchemaConfig] = useState<TFormItem[]>([])

  const resetHandle = () => {
    const resetFields = schemaConfig.map(item => ['batchAction', item.name])
    form.resetFields(resetFields)
  }

  useEffect(() => {
    setSchemaConfig(getBatchActionConfig(operationType, addressList, eventList) || [])
  }, [operationType, addressList, eventList])

  return (
    <Card
      title="批量设置"
      extra={
        <Button type="link" onClick={resetHandle}>
          清除设置
        </Button>
      }
    >
      <div className={styles.batchAction}>
        <Row wrap={false} gutter={[24, 0]} align="middle">
          {schemaConfig.map(item => {
            const deps = item.dependencies
            return (
              <Col flex={`0 0 ${100 / schemaConfig.length}%`} key={item.name}>
                <Form.Item
                  noStyle
                  shouldUpdate={(prev, cur) => {
                    // 当未配置依赖时，尽量减少不必要重渲染，仅在 batchAction 引用变化时更新
                    if (!deps || deps.length === 0) {
                      return (prev as any)?.['batchAction'] !== (cur as any)?.['batchAction']
                    }
                    // 当配置了依赖时，仅在依赖字段变化时更新
                    return deps.some(d => (prev as any)?.['batchAction']?.[d] !== (cur as any)?.['batchAction']?.[d])
                  }}
                >
                  {({ getFieldValue }) => {
                    const record = getFieldValue(['batchAction']) as IBatchAction | undefined
                    const hidden = typeof item.hidden === 'function' ? item.hidden(record) : item.hidden
                    if (hidden) return null

                    const computedLabel = typeof item.label === 'function' ? item.label(record) : item.label
                    const computedProps =
                      typeof item.componentProps === 'function' ? item.componentProps(record) : item.componentProps

                    return (
                      <Form.Item name={['batchAction', item.name]} label={computedLabel} layout="vertical">
                        <item.component {...computedProps} style={{ width: '100%' }} record={record} />
                      </Form.Item>
                    )
                  }}
                </Form.Item>
              </Col>
            )
          })}
        </Row>
      </div>
    </Card>
  )
}
